def extendList(val, list=[]): list.append(val) return list list1 = extendList(10) list2 = extendList(123,[]) list3 = extendList('a') print "list1 = %s" % list1 print "list2 = %s" % list2 print "list3 = %s" % list3
list1 = [10, 'a'] list2 = [123] list3 = [10, 'a']
letter = "hai sethuraman" for i in letter: if i == "a": pass print("pass statement is execute ..............") else: print(i)
import os print (os.path.expanduser('~'))
/home/runner
Immutable built-in datatypes of Python Numbers Strings Tuples
Mutable built-in datatypes of Python List Dictionaries Sets
import re print(re.search(r"[0-9a-zA-Z.]+@[a-zA-Z]+\.(com|co\.in)$","micheal.pages@mp.com"))
list = ['a', 'b', 'c', 'd', 'e'] print (list[10:])
for i in range(5): print(i)
The range() function accompanies two sets of parameters. range(stop) stop: It is the no. of integers to generate and starts from zero. eg. range(3) == [0, 1, 2]. range([start], stop[, step]) Start: It is the starting no. of the se
Program 0 1 2 3 4 5
Signature: id(object) It accepts one parameter and returns a unique identifier associated with the input object.
# Python code to demonstrate # *args for dynamic arguments def fn(*argList): for argx in argList: print (argx) fn('I', 'am', 'Learning', 'Python')
The output: I am Learning Python
The output: John's age is 25. Kalley's age is 22. Tom's age is 32.
print("Welcome") print("__name__ contains: ", __name__) def main(): print("Testing the main function") if __name__ == '__main__': main()
The output: Welcome __name__ contains: __main__ Testing the main function
To see whether the main() gets called, we can use the __name__ variable in an if clause compares with the value “__main__.”
# Example: Print a instead of the new line in the end. print("Let's learn" , end = ' ') print("Python") # Printing a dot in the end. print("Learn to code from techbeamers" , end = '.') print("com", end = ' ')
The output is: Let's learn Python Learn to code from techbeamers.com
>>> some_string = 'techbeamers' >>> len(some_string) 11
>>> ord("z") 122
str.rstrip([char sequence/pre> #Example test_str = 'Programming ' # The trailing whitespaces are excluded print(test_str.rstrip())
#Example str = 'pdf csv json' print(str.split(" ")) print(str.split())
The output: ['pdf', 'csv', 'json'] ['pdf', 'csv', 'json']
#Example str = 'lEaRn pYtHoN' print(str.title())
The output: Learn Python Now, check out some general purpose Python interview questions.
>>>class Human: # Create the class ... pass >>>man = Human() # Create the instance >>>print(man) <__main__.Human object at 0x0000000003559E10>
>>> class Human: ... profession = "programmer" # specify the attribute 'profession' of the class >>> man = Human() >>> print(man.profession) programmer After we added the attributes, we can go on to define the functions. Generally, we call them metho
>>> class Human: profession = "programmer" def set_profession(self, new_profession): self.profession = new_profession >>> man = Human() >>> man.set_profession("Manager") >>> print(man.profession) Manager
>>> class Human: def __init__(self, profession): self.profession = profession def set_profession(self, new_profession): self.profession = new_profession >>> man = Human("Manager") >>> print(man.profession) Manager
We do it intentionally to abstract away the similar code in different classes. The common code rests with the base class, and the child class objects can access it via inheritance. Check out the below example. class PC: # Base class processor = "Xeo
The output: Xeon Mac OS High Sierra 32 GB Xeon Windows 10 Pro 64 16 GB
To demonstrate composition, we need to instantiate other objects in the class and then make use of those instances. class PC: # Base class processor = "Xeon" # Common attribute def __init__(self, processor, ram): self.processor = processo
The output is: Tablet with i7 CPU & 16 GB ram by Intel
try: print("Executing code in the try block") print(exception) except: print("Entering in the except block") finally: print("Reached to the final block")
The output is: Executing code in the try block Entering in the except block Reached to the final block
# Example - Raise an exception while True: try: value = int(input("Enter an odd number- ")) if value%2 == 0: raise ValueError("Exited due to invalid input!!!") else: print("Value entered is : %s" % value
The output is: Enter an odd number- 2 Exited due to invalid input!!! Enter an odd number- 1 Value entered is : 1 Enter an odd number-
# Simple Python function def fn(): return "Simple Python function." # Python Generator function def generate(): yield "Python Generator function." print(next(generate()))
The output is: Python Generator function.
def multiply_number(num): def product(number): 'product() here is a closure' return num * number return product num_2 = multiply_number(2) print(num_2(11)) print(num_2(24)) num_6 = multiply_number(6) print(num_6(1))
The output is: 22 48 6
def decorator_sample(func): def decorator_hook(*args, **kwargs): print("Before the function call") result = func(*args, **kwargs) print("After the function call") return result return decorator_hook @decorator_samp
The output is: Before the function call After the function call 9
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> type(site_stats) >>> print(site_stats) {'type': 'organic', 'site': 'tecbeamers.com', 'traffic': 10000}
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> print(site_stats["traffic"]) We can even call the get method to fetch the values from a dict. It also let us set a default value. If the key is missing, then the KeyErro
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> print(site_stats.get('site')) tecbeamers.com
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> for k, v in site_stats.items(): print("The key is: %s" % k) print("The value is: %s" % v) print("++++++++++++++++++++++++")
The output is: The key is: type The value is: organic ++++++++++++++++++++++++ The key is: site The value is: tecbeamers.com ++++++++++++++++++++++++ The key is: traffic The value is: 10000 ++++++++++++++++++++++++
>>> # Setup a blank dictionary >>> site_stats = {} >>> site_stats['site'] = 'google.com' >>> site_stats['traffic'] = 10000000000 >>> site_stats['type'] = 'Referral' >>> print(site_stats) {'type': 'Referral', 'site': 'google.com', 'traffic': 10000000000}
We can even join two dictionaries to get a bigger dictionary with the help of the update() method. >>> site_stats['site'] = 'google.co.in' >>> print(site_stats) {'site': 'google.co.in'} >>> site_stats_new = {'traffic': 1000000, "type": "social media"} >>
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> del site_stats["type"] >>> print(site_stats) {'site': 'google.co.in', 'traffic': 1000000} Another method, we can use is the pop() function. It accepts the key as the par
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> print(site_stats.pop("type", None)) organic >>> print(site_stats) {'site': 'tecbeamers.com', 'traffic': 10000}
>>> site_stats = {'site': 'tecbeamers.com', 'traffic': 10000, "type": "organic"} >>> 'site' in site_stats True >>> 'traffic' in site_stats True >>> "type" in site_stats True Earlier, Python also provided the has_key() method which got deprecated.
[ expression(var) for var in iterable ] For example, the below code will return all the numbers from 10 to 20 and store them in a list. >>> alist = [var for var in range(10, 20)] >>> print(alist)
{ aKey, itsValue for aKey in iterable } For example, the below code will return all the numbers 10 to 20 as the keys and will store the respective squares of those numbers as the values. >>> adict = {var:var**2 for var in range(10, 20)} >>> print(adict)
( expression(var) for var in iterable ) For example, the below code will create a generator object that generates the values from 10 to 20 upon using it. >>> (var for var in range(10, 20)) at 0x0000000003668728> >>> list((var for var in range(10, 20)))
>>> no_of_days = 366 >>> is_leap_year = "Yes" if no_of_days == 366 else "No" >>> print(is_leap_year) Yes
enumerate(iterable, to_begin=0) Arguments: iterable: array type object which enables iteration to_begin: the base index for the counter is to get started, its default value is 0
# Example - enumerate function alist = ["apple","mango", "orange"] astr = "banana" # Let's set the enumerate objects list_obj = enumerate(alist) str_obj = enumerate(astr) print("list_obj type:", type(list_obj)) print("str_obj type:", type(str_o
Signature: globals() Arguments: None # Example: globals() function x = 9 def fn(): y = 3 z = y + x # Calling the globals() method z = globals()['x'] = z return z # Test Code ret = fn() print(ret)
The output is: 12
Signature: zip(*iterators) Arguments: Python iterables or collections (e.g., list, string, etc.) Returns: A single iterator object with combined mapped values # Example: zip() function emp = [ "tom", "john", "jerry", "jake" ] age = [ 32, 28, 33
The output is: The output of zip() is : {('jerry', 33, 'R&D'), ('jake', 44, 'IT'), ('john', 28, 'Accounts'), ('tom', 32, 'HR')}
# Example class Test: aclass = 'programming' # A class variable def __init__(self, ainst): self.ainst = ainst # An instance variable # Objects of CSStudent class test1 = Test(1) test2 = Test(2) print(test1.aclass) print(test2
The output is: programming programming 1 2 programming
[onTrue] if [Condition] else [onFalse] x, y = 35, 75 smaller = x if x < y else y print(smaller)
$ python -m pdb python-script.py
import sys def trace_calls(frame, event, arg): # The 'call' event occurs before a function gets executed. if event != 'call': return # Next, inspect the frame data and print information. print 'Function name=%s, line num=%s' % (fr
We can replace loops with generators for efficiently calculating results involving large data sets. Generators are useful when we don’t want all the results and wish to hold back for some time. Instead of using a callback function, we can repl
See the example below. def testgen(index): weekdays = ['sun','mon','tue','wed','thu','fri','sat'] yield weekdays[index] yield weekdays[index+1] day = testgen(0) print next(day), next(day) #output: sun mon
Turn a list into a string. We can use the ”.join() method which combines all elements into one and returns as a string. weekdays = ['sun','mon','tue','wed','thu','fri','sat'] listAsString = ' '.join(weekdays) print(listAsString) #output: sun mon tue we
Count the occurrences of an individual item. weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon'] print(weekdays.count('mon')) #output: 3 Count the occurrences of each item in the list. We’ll use the list comprehension along with the cou
Also, the NumPy arrays are superior to the built-in lists. There are a no. of reasons for this. NumPy arrays are more compact than lists. Reading and writing items is faster with NumPy. Using NumPy is more convenient than to the standard list
The first method to create an empty array. import numpy numpy.array([]) The second method to create an empty array. # Make an empty NumPy array numpy.empty(shape=(0,0)) Summary – Essential Python Interview Questions Please note that it is our commitm
We are here for you !! ask your project to Implement - Contact US : 96 77 44 38 55
Contact Us 9677443855